package com.zhsj.OkeHomeConsumption.ui.fragment.indexhome;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.bar.TitleBar;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.adapter.PersonCenterAdapter;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.empty.ShopListBean;
import com.zhsj.OkeHomeConsumption.ui.activity.PhotoActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.RestaurantActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.ClearEditText;
import com.zhsj.OkeHomeConsumption.ui.fragment.indexhome.mvp.StoreSearchPresenter;
import com.zhsj.OkeHomeConsumption.ui.fragment.indexhome.mvp.StoreSearchUIInterFace;
import com.zhsj.OkeHomeConsumption.utils.GoActivityUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * author : Xingdx
 * <p>
 * time   : 2018/10/18
 * desc   : 首页店铺检索
 */
public final class StoreSearchActivity extends MyActivity implements StoreSearchUIInterFace, View.OnClickListener {


    //店铺
    private List<ShopListBean> ShopList = null;
    private StoreSearchPresenter mPresenter;
    private ShopAdapter shopadper = null;
    private PersonCenterAdapter mAdapter;
    private TitleBar tb_copy_title;
    private ClearEditText verificationCode;
    private TextView sousuo;
    private RecyclerView recy;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_storesearch;
    }

    @Override
    protected int getTitleId() {
        return R.id.tb_copy_title;
    }

    @Override
    protected void initView() {
        recy = (RecyclerView) findViewById(R.id.recy);
        sousuo = (TextView) findViewById(R.id.sousuo);
        tb_copy_title = (TitleBar) findViewById(R.id.tb_copy_title);
        verificationCode = (ClearEditText) findViewById(R.id.verificationCode);
        tb_copy_title.setOnClickListener(this);
        verificationCode.setOnClickListener(this);
        sousuo.setOnClickListener(this);
        recy.setOnClickListener(this);
        mPresenter = new StoreSearchPresenter(getActivity(), this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        recy.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper.VERTICAL);

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.sousuo)
    public void onViewClicked() {
        String str = verificationCode.getText().toString().trim();

        if (str.equals("")) {
            toast("请输入关键字");
            return;
        }

        mPresenter.queryByKeyword(str);
    }
    @Override
    public void queryByKeyword(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONObject jsonobj = jsonOBJ.optJSONObject("data");
                JSONArray JSONARR = jsonobj.optJSONArray("jsonObj");
                // 数据对接正常
                ShopList = new Gson().fromJson(JSONARR.toString(), new
                        TypeToken<ArrayList<ShopListBean>>() {
                        }.getType());
                if(ShopList.size()!=0){
                    shopadper = new ShopAdapter();
                    recy.setAdapter(shopadper);
                }else{
                    toast("暂无数据");
                }

            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("ShopListGet", "获取推荐店铺异常");
        }
    }

    private void submit() {
        // validate
        String verificationCodeString = verificationCode.getText().toString().trim();
        if (TextUtils.isEmpty(verificationCodeString)) {
            Toast.makeText(this, "请输入", Toast.LENGTH_SHORT).show();
            return;
        }

        // TODO validate success, do something


    }

    @Override
    public void onClick(View view) {

    }


    public class ShopAdapter extends BaseQuickAdapter<ShopListBean, BaseViewHolder> {
        public ShopAdapter() {
            super(R.layout.item_index_shop, ShopList);
        }

        @Override
        protected void convert(BaseViewHolder helper, final ShopListBean item) {
            helper.setText(R.id.title_text, item.getShopName())
                    .setText(R.id.city_text, item.getCityName())
                    .setText(R.id.address_text, item.getAddress())
                    .setOnClickListener(R.id.lin, new AdapterView.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //跳转首页推荐店铺详情
                            Intent intent = new Intent(getActivity(), RestaurantActivity.class);
                            intent.putExtra("itemid", item.getId());
                            startActivity(intent);
                        }

                    });
            RecyclerView item_shop_recy = helper.itemView.findViewById(R.id.item_shop_recy);
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            //设置布局管理器
            item_shop_recy.setLayoutManager(layoutManager);

            layoutManager.setOrientation(OrientationHelper.HORIZONTAL);
            //设置Adapter
            ItemShopAdapter shopadper = new ItemShopAdapter(item.getShopInsidePicList());
            item_shop_recy.setAdapter(shopadper);

        }
    }

    public class ItemShopAdapter extends BaseQuickAdapter<String, BaseViewHolder> {

        public ItemShopAdapter(@Nullable List<String> data) {
            super(R.layout.item_shop_recy_img, data);
        }

        @Override
        protected void convert(@NonNull BaseViewHolder helper, final String item) {
            ImageView img = helper.itemView.findViewById(R.id.image);
            Glide.with(getActivity()).load(item).placeholder(R.drawable.zhanweitu_bg).into(img);
            img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    GoActivityUtils.GoPhotoViewpagerActivity
                            (PhotoActivity.createCircleIntent(getActivity(), Collections.singletonList(item), 0, "1")
                                    , getActivity()
                                    , v
                            );
                }
            });
        }
    }
}